package cn.lzx.lock.condition;

import cn.lzx.lock.domain.User;
import cn.lzx.lock.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by lizhenxing on 2018/1/10.
 * 没有死锁
 */
@Service
public class MysqlUniqueIndexDeadLock {

    @Autowired
    private UserService userService;


    public void saveUser() {

        userService.deleteAll();

        User user = new User();
        user.setId(1L);
        user.setUsername("lizhenxing");
        user.setPassword("hhh");
        user.setAge(1);
        user.setHomeTown("tianjin");
        user.setIdentity("56789");
        user.setSex(User.Sex.MAN);

        User u = new User();
        u.setId(2L);
        u.setUsername("abc");
        u.setPassword("hhh");
        u.setAge(1);
        u.setHomeTown("beijing");
        u.setIdentity("12345");
        u.setSex(User.Sex.MAN);

        userService.save(u);
        userService.save(user);
    }

    private volatile AtomicBoolean flag = new AtomicBoolean();

    @Transactional
    public void updateA() {
        userService.update("12345", "lizhenxing");
        while (!flag.get()) {
        }
        userService.update("56789", "hhh");
    }

    @Transactional
    public void updateB() {
        userService.update("56789", "lizhenxing");
        while (!flag.get()) {
        }
        userService.update("12345", "fsdfsdf");
    }

    public void switchOn() {
        flag.set(true);
    }
}
